//package org.example.cet.demos.service.impl;
//
//import cn.hutool.core.util.StrUtil;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import lombok.RequiredArgsConstructor;
//import org.example.cet.demos.domain.PageBean;
//import org.example.cet.demos.domain.po.Classroom;
//import org.example.cet.demos.domain.po.Papers;
//import org.example.cet.demos.domain.query.ClassroomQuery;
//import org.example.cet.demos.domain.query.PapersQuery;
//import org.example.cet.demos.mapper.PapersMapper;
//import org.example.cet.demos.service.IPapersService;
//import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import org.springframework.stereotype.Service;
//
///**
// * <p>
// *  服务实现类
// * </p>
// *
// * @author hq
// * @since 2024-12-18
// */
//@Service
//@RequiredArgsConstructor
//public class PapersServiceImpl extends ServiceImpl<PapersMapper, Papers> implements IPapersService {
//    public PageBean getPage(PapersQuery papersQuery){
//        Page<Papers> page=new Page<>(papersQuery.getCurrentPage(), papersQuery.getPageSize());
//        lambdaQuery().like(Papers::getId,papersQuery.getId())
//                .like(papersQuery.getLevel()!=null,Papers::getLevel,papersQuery.getLevel())
//                .like(papersQuery.getYear()!=null,Papers::getYear,papersQuery.getYear())
//                .like(papersQuery.getMonth()!=null,Papers::getMonth,papersQuery.getMonth())
//                .page(page);
//        PageBean pageBean=new PageBean();
//        pageBean.setTotal(page.getTotal());
//        pageBean.setRows(page.getRecords());
//        return pageBean;
//    }
//}
package org.example.cet.demos.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import lombok.RequiredArgsConstructor;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.example.cet.demos.domain.PageBean;
import org.example.cet.demos.domain.dto.PapersDto;
import org.example.cet.demos.domain.po.Options;
import org.example.cet.demos.domain.po.Papers;
import org.example.cet.demos.domain.po.Questions;
import org.example.cet.demos.domain.query.PapersQuery;
import org.example.cet.demos.mapper.PapersMapper;
import org.example.cet.demos.service.IPapersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hq
 * @since 2024-12-18
 */
@Service
@RequiredArgsConstructor
public class PapersServiceImpl extends ServiceImpl<PapersMapper, Papers> implements IPapersService {
    @Override
    public PageBean getPage(PapersQuery papersQuery) {
        // 创建 Page 对象，设置当前页和每页记录数
        Page<Papers> page = new Page<>(papersQuery.getCurrentPage(), papersQuery.getPageSize());
        // 使用 lambdaQuery 进行条件查询并分页
        lambdaQuery()
                .like(papersQuery.getId() != null, Papers::getId, papersQuery.getId())
                .like(StrUtil.isNotBlank(papersQuery.getTitle()), Papers::getTitle, papersQuery.getTitle())
                .like(StrUtil.isNotBlank(papersQuery.getType()), Papers::getType, papersQuery.getType())
                .like(StrUtil.isNotBlank(papersQuery.getYear()), Papers::getYear, papersQuery.getYear())
                .page(page);

        // 创建 PageBean 对象并设置总记录数和记录列表
        PageBean pageBean = new PageBean();
        pageBean.setTotal(page.getTotal());
        pageBean.setRows(page.getRecords());
        return pageBean;
    }
    @Autowired
    private PapersMapper papersMapper;
//    @Override
//    public List<PaperDto> getPaper(Long id) {
//        return papersMapper.getPaper(id);
//    }
//    public List<PapersDto> getList(){
//        return papersMapper.getList();
//    }

    @Override
    public List<Map<String,Object>> getPaper(Long id) {
        return papersMapper.getPaper(id);
    }

    @Transactional
    public void delete(Long id){
        papersMapper.delete(id);
    }
    @Override
    public int insertPaper(Papers paper) {
        papersMapper.insertPaper(paper);
        return Math.toIntExact(paper.getId());
    }

    @Override
    public int insertQuestion(Questions question) {
        papersMapper.insertQuestion(question);
        return question.getId();
    }

    @Override
    public void insertOptions(Options options) {
        papersMapper.insertOptions(options);
    }

    @Override
    public List<PapersDto> getPaperList(){
        return papersMapper.getPaperList();
    }

    @Override
    public String handleFileUpload(MultipartFile file, String title, String paperType, String year, String answer) {
        if (file.isEmpty()) {
            return "文件为空";
        }


        Papers paper = new Papers();
        paper.setTitle(title);
        paper.setType(paperType);
        paper.setYear(year);
        int paperId = insertPaper(paper);

//        String[] lAnswer = Arrays.copyOfRange(answer,0,25);
//        String[] RaAnswer= Arrays.copyOfRange(answer,26,35);
//        String[] RbAnswer= Arrays.copyOfRange(answer,36,45);
//        String[] RcAnswer= Arrays.copyOfRange(answer,46,55);



        try (PDDocument document = PDDocument.load(file.getInputStream())) {
            PDFTextStripper pdfStripper = new PDFTextStripper();
            String text = pdfStripper.getText(document);

            String[] parts = text.split("\\(30minutes\\)|\\(25 minutes\\)|\\( 40 minutes \\)|\\(30 minutes\\)");

            if (parts.length < 5) {
                return "文件格式不符合要求，无法解析";
            }

            // 处理写作部分
            String[] writingContent = parts[1].split("\\\n");
            StringBuilder writing = new StringBuilder();
            for (int i = 0; i < writingContent.length - 1; i++) {
                writing.append(writingContent[i]).append("\n");
            }
            Questions writingQuestion = new Questions();
            writingQuestion.setType(0);
            writingQuestion.setContent(writing.toString());
            writingQuestion.setPaper_id(paperId);
            int writingQuestionId = insertQuestion(writingQuestion);

            Options writingOptions = new Options();
            writingOptions.setQuestion_id(writingQuestionId);
            writingOptions.setText(null);
//            readAOptions.setAnswer(null);
            insertOptions(writingOptions);

            // 处理听力部分
            String regex = "[A-Z]\\)\\s*[A-Z][a-zA-Z ].*";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(parts[2]);
            StringBuilder listeningString = new StringBuilder();
            while (matcher.find()) {
                listeningString.append(matcher.group(0));
            }
            Questions listeningQuestion = new Questions();
            listeningQuestion.setType(1);
//            listeningQuestion.setContent(listeningString.toString());
            listeningQuestion.setContent(null);
            listeningQuestion.setPaper_id(paperId);
            listeningQuestion.setAnswer(answer.substring(0,25));
            int listeningQuestionId = insertQuestion(listeningQuestion);

            String[] listeningArray = listeningString.toString().split("\\.|,|，");
            ArrayList<String> all = new ArrayList<>();
            for (int i = 0; i < listeningArray.length; i += 4) {
                String[] a = new String[4];
                for (int j = 0; j < 4; j++) {
                    if (i + j < listeningArray.length) {
                        a[j] = listeningArray[i + j];
                    }
                }
                all.add(Arrays.toString(a));
            }
            Options listeningOptions = new Options();
            listeningOptions.setQuestion_id(listeningQuestionId);
            listeningOptions.setText(new Gson().toJson(all));
//            listeningOptions.setAnswer(null);
            insertOptions(listeningOptions);

            // 处理阅读部分
            String[] readingContent = parts[3].split("Questions 26 to 35 are based on the following passage.|" +
                    "Directions: In this section, you are going to read a passage with ten statements attached to|" +
                    "marking the corresponding letter onAnswer Sheet 2.|" +
                    "Directions: There are 2 passages in this section. Each passage is followed by|" +
                    "50 are based on the following passage.|" +
                    "Passage Two");

            if (readingContent.length < 7) {
                return "文件格式不符合要求，无法解析阅读部分";
            }

            // 阅读部分 A
            String SectionA = readingContent[1].substring(0, readingContent[1].trim().length() - 9);


            String r1 = "[A-D]\\) .+(?:\\r?\\n|\\r)?(?:[^A-D\\d].+(?:\\r?\\n|\\r)?)*";
            Pattern p1 = Pattern.compile(r1);
            Matcher m1 = p1.matcher(SectionA);
            StringBuilder wordString = new StringBuilder();
            while (m1.find()) {
                wordString.append(m1.group());
            }

            //插入纯文本
            String textARegex = "[A-D]\\) .+(?:\\r?\\n|\\r)?(?:[^A-D\\d].+(?:\\r?\\n|\\r)?)*";
            Pattern p1_2 = Pattern.compile(textARegex);
            Matcher m1_2 = p1_2.matcher(SectionA);
            String textA="";
            if (m1_2.find()) {
                int startIndex = m1_2.start();
                textA = SectionA.substring(0, startIndex);
            }
            textA = textA.replaceAll("(?m)^\\s*$[\n\r]{1,}", "");
            Questions readAQuestion = new Questions();
            readAQuestion.setType(2);
            readAQuestion.setContent(textA);
            readAQuestion.setPaper_id(paperId);
            readAQuestion.setAnswer(answer.substring(25,35));
            int readAQuestionId = insertQuestion(readAQuestion);


            String r1_1 = "[A-Z]\\) [a-zA-Z]+";
            Pattern p1_1 = Pattern.compile(r1_1);
            Matcher m1_1 = p1_1.matcher(wordString);
            List<String> words = new ArrayList<>();
            while (m1_1.find()) {
                words.add(m1_1.group());
            }
            Comparator<String> optionComparator = (o1, o2) -> {
                char char1 = o1.charAt(0);
                char char2 = o2.charAt(0);
                return Character.compare(char1, char2);
            };
            Collections.sort(words, optionComparator);

            Options readAOptions = new Options();
            readAOptions.setQuestion_id(readAQuestionId);
            readAOptions.setText(new Gson().toJson(words));
//            readAOptions.setAnswer(null);
            insertOptions(readAOptions);

            //阅读部分B篇
            String SectionB = readingContent[3].substring(0, readingContent[3].trim().length() - 9);

            String textBRegex = "\\d+\\. .+";
            Pattern p2_1 = Pattern.compile(textBRegex);
            Matcher m2_1 = p2_1.matcher(SectionB);
            //纯文本
            String textB="";
            if (m2_1.find()) {
                int startIndex = m2_1.start();
                textB = SectionB.substring(0, startIndex);
            }
            textB = textB.replaceAll("(?m)^\\s*$[\n\r]{1,}", "");
            Questions readBQuestion = new Questions();
            readBQuestion.setType(3);
            readBQuestion.setContent(textB);
            readBQuestion.setPaper_id(paperId);
            readBQuestion.setAnswer(answer.substring(35,45));
            int readBQuestionId = insertQuestion(readBQuestion);
            //选项
            String titleB = "\\d+\\. .+";
            Pattern p2 = Pattern.compile(titleB);
            Matcher m2 = p2.matcher(SectionB);

            StringBuilder qsBString = new StringBuilder();
            while (m2.find()) {
                String optionValue = m2.group();
                qsBString.append(optionValue).append("\n");
            }
            String qsBResult = qsBString.toString();
            String[] qsBArray = qsBResult.split("\n");
            Options readBOptions = new Options();
            readBOptions.setQuestion_id(readBQuestionId);
            readBOptions.setText(new Gson().toJson(qsBArray));
//            readAOptions.setAnswer(null);
            insertOptions(readBOptions);

            //阅读部分C篇
            String SectionC_One = readingContent[5];//c1

            String textRegex = "\\d+\\. .+";
            Pattern textC1Pattern = Pattern.compile(textRegex);
            Matcher textC1Matcher = textC1Pattern.matcher(SectionC_One);
            String textC1 = "";
            if (textC1Matcher.find()) {
                int startIndex = textC1Matcher.start();
                textC1 = SectionC_One.substring(0, startIndex);
            }
            textC1 = textC1.replaceAll("(?m)^\\s*$[\n\r]{1,}", "");
            Questions readC1Question = new Questions();
            readC1Question.setType(4);
            readC1Question.setContent(textC1);
            readC1Question.setPaper_id(paperId);
            readC1Question.setAnswer(answer.substring(45,50));
            int readC1QuestionId = insertQuestion(readC1Question);


            String titleC = "\\d+\\. .+";
            Pattern p3_1 = Pattern.compile(titleC);
            Matcher m3_1 = p3_1.matcher(SectionC_One);
            StringBuilder qs1String = new StringBuilder();
            while (m3_1.find()) {
                String optionValue = m3_1.group();
                qs1String.append(optionValue).append("\n");
            }
            String qs1Result = qs1String.toString();
            String[] qs1Array = qs1Result.split("\n");

            String chooseC = "[A-D]\\) .+(?:\\r?\\n|\\r)?(?:[^A-D\\d].+(?:\\r?\\n|\\r)?)*";
            Pattern p3_2 = Pattern.compile(chooseC);
            Matcher m3_2 = p3_2.matcher(SectionC_One);

            StringBuilder chooseString = new StringBuilder();
            while (m3_2.find()) {
                String optionValue = m3_2.group();
                chooseString.append(optionValue).append("\n");
            }

            String[] chooseSZ = chooseString.toString().split("\r\n\n");


            ArrayList<String[]> group3_2 = new ArrayList<>();
            for (int i = 0; i < chooseSZ.length; i += 4) {
                String[] smallArray = new String[4];
                for (int j = 0; j < 4; j++) {
                    if (i + j < chooseSZ.length) {
                        smallArray[j] = chooseSZ[i + j];
                    }
                }
                group3_2.add(smallArray);
            }

            ArrayList<Map<String, Object>> c1 = new ArrayList<>();
            for (int j = 0; j < 5; j++) {
                if (j < qs1Array.length && j < group3_2.size()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("title", qs1Array[j]);
                    map.put("select", group3_2.get(j));
                    c1.add(map);
                }
            }
            Options readC1Options = new Options();
            readC1Options.setQuestion_id(readC1QuestionId);
            readC1Options.setText(new Gson().toJson(c1));
            insertOptions(readC1Options);




            String SectionC_Two = readingContent[6].substring(0, readingContent[6].length() - 18);//c2


            Pattern textC2Pattern = Pattern.compile(titleC);
            Matcher textC2Matcher = textC2Pattern.matcher(SectionC_Two);
            String textC2 = "";
            if (textC2Matcher.find()) {
                int startIndex = textC2Matcher.start();
                textC2 = SectionC_Two.substring(0, startIndex);
            }
            textC2 = textC2.replaceAll("(?m)^\\s*$[\n\r]{1,}", "");
            Questions readC2Question = new Questions();
            readC2Question.setType(4);
            readC2Question.setContent(textC2);
            readC2Question.setPaper_id(paperId);
            readC2Question.setAnswer(answer.substring(50,55));
            int readC2QuestionId = insertQuestion(readC2Question);

            Matcher m3_3 = p3_1.matcher(SectionC_Two);
            StringBuilder qs2String = new StringBuilder();
            while (m3_3.find()) {
                String optionValue = m3_3.group();
                qs2String.append(optionValue).append("\n");
            }
            String qs2Result = qs2String.toString();
            String[] qs2Array = qs2Result.split("\n");

            Matcher m3_4 = p3_2.matcher(SectionC_Two);
            StringBuilder choose2String = new StringBuilder();
            while (m3_4.find()) {
                String optionValue = m3_4.group();
                choose2String.append(optionValue).append("\n");
            }
            String[] choose2SZ = choose2String.toString().split("\r\n\n");

            ArrayList<String[]> group3_4 = new ArrayList<>();
            for (int i = 0; i < choose2SZ.length; i += 4) {
                String[] smallArray = new String[4];
                for (int j = 0; j < 4; j++) {
                    if (i + j < choose2SZ.length) {
                        smallArray[j] = choose2SZ[i + j];
                    }
                }
                group3_4.add(smallArray);
            }

            ArrayList<Map<String, Object>> c2 = new ArrayList<>();
            for (int j = 0; j < 5; j++) {
                if (j < qs2Array.length && j < group3_4.size()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("title", qs2Array[j]);
                    map.put("select", group3_4.get(j));
                    c2.add(map);
                }
            }
            Options readC2Options = new Options();
            readC2Options.setQuestion_id(readC2QuestionId);
            readC2Options.setText(new Gson().toJson(c2));
            insertOptions(readC2Options);


            //翻译部分
            String Translation = parts[4];
            Questions translation = new Questions();
            translation.setType(5);
            translation.setContent(Translation);
            translation.setPaper_id(paperId);
            translation.setAnswer(null);

            int translationId = insertQuestion(translation);
            Options translationOptions = new Options();
            translationOptions.setQuestion_id(translationId);
            translationOptions.setText(null);
//            readAOptions.setAnswer(null);
            insertOptions(translationOptions);

            return "文件内容上传成功，试卷 ID: " + paperId;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件解析失败";
        }
    }

//    @Override
//    public List<Questions> getQuestionsByType(int type) {
//        return papersMapper.getQuestionsByType(type);
//    }
//
//    @Override
//    public List<Questions> getQuestionsByPaperId(int paperId) {
//        return papersMapper.getQuestionsByPaperId(paperId);
//    }
}